package com.ly.hotel.timetask;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.GsonBuilder;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.model.ModelBean;
import com.ly.hotel.msgevent.ActionTimeTickEvent;
import com.ly.hotel.service.SPABackService;
import com.ly.hotel.service.SPAService;

import java.lang.ref.WeakReference;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;

public class ServerTimeTimerTask extends TimerTask{
	private ThisHandler handler = new ThisHandler(this);
	private static MyApplication app = (MyApplication) MyApplication.getContext();
	@Override
	public void run() {
		Message message = new Message();
        message.what=1;
        handler.sendMessage(message);
	}

	private static class ThisHandler extends Handler {
		private WeakReference<ServerTimeTimerTask> wrActivity;

		public ThisHandler(ServerTimeTimerTask activity) {
			wrActivity = new WeakReference<ServerTimeTimerTask>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			super.handleMessage(message);
            if(message.what==1) {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/now.json";

					StringRequest  stringRequest = new StringRequest(Request.Method.GET, url,
			                 new Response.Listener<String>() {
			                     @Override
			                     public void onResponse(String response) {
									 Log.i("time", "服务器时间->>" + response);
									 MyApplication.serverAssess = true;
									 ModelBean d = new GsonBuilder().create().fromJson(response, ModelBean.class);

									 if (d != null) {
										 if (!d.getCode().equals(-1) && d.getData() != null && !d.getData().equals("")){
											 app.nowTime = d.getData().toString();
											 EventBus.getDefault().post(new ActionTimeTickEvent());
										 }
									 }
			                     }
			                 }, new Response.ErrorListener() {
			                     @Override
			                     public void onErrorResponse(VolleyError error) {
			                    	 Log.e("time", "获取服务器时间失败." + error.getMessage());
			                     }
			                 });
					stringRequest.setTag("time");
					stringRequest.setShouldCache(false);
					SPABackService.mQueue.add(stringRequest);
				} catch (Exception e) {
					Log.e("heart", "SPAService.serverTime:" + e.getMessage());
				}
            }
		}
	}
}
